import { getRepository, MigrationInterface, In } from 'typeorm'

const SystemUser = [
  {
    username: 'superman',
    nickname: '张三疯',
    phone: '15612341234',
    email: 'zsf@in-echo.com',
    password: '$2b$10$/MvtAREdf7LB4JY/dDkByerQU.l6/202eHzvcDIR4B5Una4dKvF4S',
    active: true
  }
]

const SystemUserRole = [
  {
    rolename: '超级管理员',
    role: 'admin'
  },
  {
    rolename: '管理员',
    role: 'system-user'
  },
  {
    rolename: '审核员',
    role: 'auditor'
  },
  {
    rolename: '录入员',
    role: 'operator'
  },
  {
    rolename: '民警',
    role: 'police'
  }
]

const User = [
  {
    username: 'ceshi001',
    nickname: '测试账号001',
    realname: '吴用',
    remark: '这是一个初始化生成的测试账号',
    phone: '15611112222',
    email: 'ceshi001@in-echo.com',
    password: '$2b$10$/MvtAREdf7LB4JY/dDkByerQU.l6/202eHzvcDIR4B5Una4dKvF4S',
    active: true
  }
]

const UserRole = [
  {
    rolename: '注册会员',
    role: 'user'
  },
  {
    rolename: '游客',
    role: 'anonymous'
  }
]

export class Init1634388507616 implements MigrationInterface {

  public async up(): Promise<void> {
    try {
      const systemRoleRepository = getRepository('ie_system_user_role')
      const systemUserRepository = getRepository('ie_system_user')
      const systemUserMetaRepository = getRepository('system_user_meta')
      const [sytemUserRole]: any[] = await systemRoleRepository.save(SystemUserRole)

      const [systemUser] = await systemUserRepository.save(
        SystemUser.map(v => ({ ...v, role: sytemUserRole }))
      )
      await systemUserMetaRepository.save({
        system_user: systemUser
      })
    } catch (err) {}

    try {
      const roleRepository = getRepository('ie_user_role')
      const userRepository = getRepository('ie_user')
      const [userRole]: any[] = await roleRepository.save(UserRole)

      await userRepository.save(
        User.map(v => ({ ...v, role: userRole }))
      )
    } catch (err) {}
  }

  public async down(): Promise<void> {
    try {
      const systemRoleRepository = getRepository('ie_system_user_role')
      const systemUserRepository = getRepository('ie_system_user')
      const roleRepository = getRepository('ie_user_role')
      const userRepository = getRepository('ie_user')

      await systemUserRepository.delete({
        username: In(SystemUser.map(v => v.username))
      })
      await userRepository.delete({
        username: In(User.map(v => v.username))
      })
      await systemRoleRepository.delete({
        role: In(SystemUserRole.map(v => v.role))
      })
      await roleRepository.delete({
        role: In(UserRole.map(v => v.role))
      })
    } catch (err) {}
  }
}
